package com.shuaqiu.sboot.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.shuaqiu.sboot.common.bean.Result;
import com.shuaqiu.sboot.login.bean.LoginForm;
import com.shuaqiu.sboot.login.bean.LoginUserVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    private static final String LOGIN_USER = "login_user";

    private LoginService loginService;

    @Autowired
    public void setLoginService(final LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 获取当前登录的用户信息
     *
     * @param webSession session
     * @return 当前登录的用户信息
     */
    @ApiOperation(value = "获取当前登录用户信息", notes = "获取当前登录的用户信息, 如果没有登录, 则返回错误信息")
    @GetMapping("/login")
    public Result<LoginUserVo> getLoginUser(final HttpSession webSession) {
        final LoginUserVo loginUserVo = (LoginUserVo) webSession.getAttribute(LOGIN_USER);
        if (loginUserVo == null) {
            return new Result<>(false, "尚未登录", null);
        }

        return new Result<>(true, "已登录", loginUserVo);
    }

    /**
     * 登录操作
     *
     * @param request request
     * @param loginForm  登录账户信息
     * @return 登录结果
     */
    @ApiOperation(value = "进行登录", notes = "根据提交的用户账号和密码, 进行登录操作")
    @PostMapping("/login")
    public Result<LoginUserVo> login(final HttpServletRequest request, @Valid @RequestBody final LoginForm loginForm) {
        final LoginUserVo loginUserVo = loginService.login(loginForm.getAccount(), loginForm.getPassword());
        if (loginUserVo == null) {
            return new Result<>(false, "登录失败", loginUserVo);
        }

        request.getSession().invalidate();
        final HttpSession session = request.getSession(true);
        session.setAttribute(LOGIN_USER, loginUserVo);
        return new Result<>(true, "登录成功", loginUserVo);
    }

    /**
     * 注销登录
     *
     * @param webSession session
     * @return 注销结果
     */
    @DeleteMapping("/login")
    public Result<Boolean> logout(final HttpSession webSession) {
        // 使session 无效
        webSession.invalidate();
        return new Result<>(false, "已注销登录", true);
    }
}
